class Solution {
public:
    bool canFinish(int n, vector<vector<int>>& edges) {
        vector<vector<int>> g(n);
        vector<int> deg(n);
        for (auto e : edges) {
            int a = e[1], b = e[0];
            g[a].push_back(b);
            deg[b] ++;
        }

        queue<int> q;
        for (int i = 0; i < n; i ++) {
            if (deg[i] == 0) {
                q.push(i);
            }
        }

        int cnt = 0;
        while (q.size()) {
            auto t = q.front();
            q.pop();
            cnt ++;
            for (auto v : g[t]) {
                -- deg[v];
                if (deg[v] == 0) {
                    q.push(v);
                }
            }
        }
        return cnt == n;
    }
};